import time
from datetime import datetime
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from pet_admin.models import Orders_Main, Users, Goods, OrderSub


def find(request, pageIndex=1):
    """
        查询全部订单信息视图
    """
    order_sub = OrderSub.objects  # 实例化Orders对象
    orderSubs = order_sub.filter(orderSub_status__lt=9).order_by('orderSub_id')  # 过滤出来状态小于9的有效订单
    searchKey = []
    # 获取并判断搜索条件
    user_name = request.GET.get("user_name", None)  # 获取表单提交数据
    if user_name:
        user_name = user_name.replace(" ", "")
        orderSubs = orderSubs.filter(user_id__user_name__contains=user_name)
        searchKey.append("user_name=" + user_name)

    order_id = request.GET.get("order_id", None)  # 获取表单提交数据
    if order_id:
        orderSubs = orderSubs.filter(order_id=order_id)
        searchKey.append("order_id=" + order_id)

    good_name = request.GET.get("good_name", None)  # 获取表单提交数据
    if good_name:
        orderSubs = orderSubs.filter(good_id__good_name__contains=good_name)
        searchKey.append("good_name=" + good_name)

    # 分页处理
    pageIndex = int(pageIndex)
    page = Paginator(orderSubs, 10)  # 每页多少条
    maxPage = page.num_pages  # 获取最大页数
    # 处理页码越界
    if pageIndex > maxPage:
        pageIndex = maxPage
    if pageIndex < 1:
        pageIndex = 1
    orderSubs = page.page(pageIndex)  # 获取当前页数据
    pages = page.page_range  # 获取页码列表信息

    # 遍历当前商品信息并封装对应的商品类型
    for order in orderSubs:
        user = Users.objects.get(user_id=order.user_id)
        order.user_name = user.user_name

        good = Goods.objects.get(good_id=order.good_id)
        order.good_name = good.good_name

    context = {"orderSubs": orderSubs, "pages": pages, "pageIndex": pageIndex, "maxPage": maxPage,
               "searchKey": searchKey, "order_id": order_id}
    return render(request, 'pet_admin/order_manage/orderSub_index.html', context)


def deluser(request, orderSub_id):
    """
       执行删除程序的方法
    """
    try:
        orderSubs = Orders_Main.objects.get(orderSub_id=orderSub_id)
        orderSubs.orderSub_status = 9
        orderSubs.orderSub_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        orderSubs.save()
        context = {"info": "删除成功"}

    except Exception as err:
        print(err)
        context = {"info": "删除失败"}

    return render(request, "pet_admin/info.html", context)
